package com.wangzhenyu.learn.test.designPattern


//观察者模式


@Suppress("UNUSED")
object RObservePattern {

    //观察者
    interface Observer {

        fun update(temperature: Float, pressure: Float, humidity: Float)
    }

    //具体观察者
    class CurrentConditions : Observer {

        private var temperature: Float = 0.0f
        private var pressure: Float = 0.0f
        private var humidity: Float = 0.0f

        override fun update(temperature: Float, pressure: Float, humidity: Float) {
            this.temperature = temperature
            this.pressure = pressure
            this.humidity = humidity
            display()
        }

        private fun display() {
            println("Today Temperature :$temperature")
            println("Today Pressure :$pressure")
            println("Today Humidity :$humidity")
        }

    }

    //被观察者
    interface Subject {

        fun registerObserver(observer: Observer)

        fun removeObserver(observer: Observer)

        fun notifyObserver()
    }

    //具体的被观察者
    class WeatherData() : Subject {

        private var temperature: Float = 0.0f
        private var pressure: Float = 0.0f
        private var humidity: Float = 0.0f

        private val observers: MutableList<Observer> = mutableListOf()

        fun setData(temperature: Float, pressure: Float, humidity: Float) {
            this.temperature = temperature
            this.pressure = pressure
            this.humidity = humidity
            notifyObserver()
        }

        override fun registerObserver(observer: Observer) {
            observers.add(observer)
        }

        override fun removeObserver(observer: Observer) {
            if (observers.contains(observer)) observers.remove(observer)
        }

        override fun notifyObserver() {
            for (i in observers) {
                i.update(temperature, pressure, humidity)
            }
        }


    }

}